import os

class ReadTxt:
    def __init__(self, txt_file):
        base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        self.txt_file = os.path.join(base_dir, "file", txt_file)

    # 读取txt文件
    def load_txt_content(self):
        try:
            if not os.path.exists(self.txt_file):
                return "使用默认文本内容"

            with open(self.txt_file, 'r', encoding='utf-8') as file:
                text = file.read()
                return text.strip()

        except Exception as e:
            return str(e)

    # 按行读取txt文件
    def load_txt_lines(self):
        try:
            if not os.path.exists(self.txt_file):
                return ["使用默认文本内容"]

            with open(self.txt_file, 'r', encoding='utf-8') as file:
                lines = file.readlines()
                # 去除每行末尾的换行符
                lines = [line.strip() for line in lines]
                return lines

        except Exception as e:
            return [str(e)]

    # 读取指定行数的内容
    def load_txt_limited(self, max_lines=100):
        try:
            if not os.path.exists(self.txt_file):
                return "使用默认文本内容"

            with open(self.txt_file, 'r', encoding='utf-8') as file:
                lines = []
                for i, line in enumerate(file):
                    if i >= max_lines:
                        break
                    lines.append(line.strip())
                return '\n'.join(lines)

        except Exception as e:
            return str(e)
